package com.itany.ums.dao.impl;

import java.util.ArrayList;
import java.util.List;

import com.itany.ums.dao.UserDao;
import com.itany.ums.entity.User;

import data.Datasource;

public class UserDaoImpl implements UserDao {

	// dao只考虑怎样查找数据
	// 不关心service拿到数据之后怎么用
	@Override
	public User selectByLoginnameAndPassword(String loginname, String password) {
		for (int i = 0; i < Datasource.users.length; i++) {
			User u = Datasource.users[i];
			if ((u.getUsername().equals(loginname) || u.getPhone().equals(loginname) || u.getEmail().equals(loginname)) && u.getPassword().equals(password)) {
				return (User) u.clone();
			}
		}
		return null;
	}

	@Override
	public User selectByUsername(String username) {
		for (int i = 0; i < Datasource.users.length; i++) {
			User u = Datasource.users[i];
			if (u.getUsername().equalsIgnoreCase(username)) {
				return (User) u.clone();
			}
		}
		return null;
	}

	@Override
	public User selectByPhone(String phone) {
		for (int i = 0; i < Datasource.users.length; i++) {
			User u = Datasource.users[i];
			if (u.getPhone().equals(phone)) {
				return (User) u.clone();
			}
		}
		return null;
	}

	@Override
	public User selectByEmail(String email) {
		for (int i = 0; i < Datasource.users.length; i++) {
			User u = Datasource.users[i];
			if (u.getEmail().equals(email)) {
				return (User) u.clone();
			}
		}
		return null;
	}

	@Override
	public void saveUser(User u) {
		u.setId(Datasource.id++);
		Datasource.saveUser(u);
	}

	@Override
	public User selectById(long id) {
		for (int i = 0; i < Datasource.users.length; i++) {
			User u = Datasource.users[i];
			if (u.getId().equals(id)) {
				return (User) u.clone();
			}
		}
		return null;
	}

	@Override
	public void updatePwd(long id, String newPwd) {
		for (int i = 0; i < Datasource.users.length; i++) {
			User u = Datasource.users[i];
			if (u.getId().equals(id)) {
				u.setPassword(newPwd);
				return;
			}
		}
	}

	@Override
	public void updateUsername(long id, String username) {
		for (int i = 0; i < Datasource.users.length; i++) {
			User u = Datasource.users[i];
			if (u.getId().equals(id)) {
				u.setUsername(username);
				return;
			}
		}
	}

	@Override
	public List<User> selectByRole(int roleCode) {
		// User[] tmp = new User[0];
		List<User> users = new ArrayList<User>();
		for (int i = 0; i < Datasource.users.length; i++) {
			if (Datasource.users[i].getRole().equals(roleCode)) {
				// tmp = addUser(tmp, Datasource.users[i]);
				users.add((User) Datasource.users[i].clone());
			}
		}
		return users;
	}

	private User[] addUser(User[] us, User u) {
		User[] tmp = new User[us.length + 1];
		for (int i = 0; i < us.length; i++) {
			tmp[i] = us[i];
		}
		tmp[us.length] = u;
		return tmp;
	}

	@Override
	public void updateStateById(long id, int stateCode) {
		for (int i = 0; i < Datasource.users.length; i++) {
			User u = Datasource.users[i];
			if (u.getId().equals(id)) {
				u.setState(stateCode);
				return;
			}
		}
	}

}
